﻿using CommunityToolkit.Mvvm.ComponentModel;
using QModels;
using QServices;
using QServices.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using CommunityToolkit.Mvvm.Input;
using System.ComponentModel.DataAnnotations.Schema;
using MiniExcelLibs.Attributes;
using MiniExcelLibs;
using System.Windows.Forms;
using TouchSocket.Core;
using HandyControl.Controls;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Windows.Data;

namespace QControlCenter.ViewModel
{

	public partial class PigeonPageViewModel : QBaseVM
	{

		#region 鸽笼监控

		/// <summary>
		/// 鸽笼管理
		/// </summary>
		[ObservableProperty]
		private int geLongGuanLi;

		/// <summary>
		/// 空置鸽笼
		/// </summary>
		[ObservableProperty]
		private int kongZhigeLong;

		/// <summary>
		/// 查蛋
		/// </summary>
		[ObservableProperty]
		private int chaDan;

		/// <summary>
		/// 照蛋
		/// </summary>
		[ObservableProperty]
		private int zhaoDan;

		/// <summary>
		/// 查雏
		/// </summary>
		[ObservableProperty]
		private int chaChu;

		/// <summary>
		/// 出栏
		/// </summary>
		[ObservableProperty]
		private int chuLan;

		/// <summary>
		/// 淘汰
		/// </summary>
		[ObservableProperty]
		private int taoTai;

		/// <summary>
		/// 补栏
		/// </summary>
		[ObservableProperty]
		private int buLan;

		/// <summary>
		/// 调并
		/// </summary>
		[ObservableProperty]
		private int tiaoBing;

		/// <summary>
		/// 健康检查
		/// </summary>
		[ObservableProperty]
		private int jianKangJianCha;

		[ObservableProperty]
		private int tempErr;

		#endregion

		[ObservableProperty]
		private decimal maxPageCount;

		[ObservableProperty]
		private int? region;
		[ObservableProperty]
		private string? cageNumber;
		[ObservableProperty]
		private int? hasRuGe;
		[ObservableProperty]
		private int? hasDan;
		[ObservableProperty]
		private int? wenDu;
		[ObservableProperty]
		private int cageStatus;
		[ObservableProperty]
		private int pageIndex;

		public ObservableCollection<PigeonCageQuery> PigeonCages { get; set; } = new ObservableCollection<PigeonCageQuery>();
		public ObservableCollection<AreaModel> AreaModels { get; set; } = new ObservableCollection<AreaModel>
		{
				new AreaModel{Name="全部",Value=""},
				new AreaModel{Name="A区",Value="A"},
				new AreaModel{Name="B区",Value="B"},
				new AreaModel{Name="C区",Value="C"},
				new AreaModel{Name="D区",Value="D"},
				new AreaModel{Name="E区",Value="E"}
		};
		public string[] AreaArray = new string[] { "", "A", "B", "C", "D", "E" };
		public ObservableCollection<UseModel> HasOrNoArray { get; set; } = new ObservableCollection<UseModel>
		{
			new UseModel{Name="全部",Value=0},
			new UseModel{Name="无",Value=1},
			new UseModel{Name="有",Value=2}
		};

		public ObservableCollection<UseModel> WenDus { get; set; } = new ObservableCollection<UseModel>
		{
			new UseModel{Name="全部",Value=0},
			new UseModel{Name="正常温度",Value=1},
			new UseModel{Name="异常温度",Value=2}
		};
		public ObservableCollection<UseModel> CageStatusList { get; set; } = new ObservableCollection<UseModel>
		{
			new UseModel{Name="所有",Value=0},
			new UseModel{Name="空置鸽笼",Value=1 },
			new UseModel{Name="查蛋",Value=2},
			new UseModel{Name="照蛋",Value=3},
			new UseModel{Name="查雏",Value=4},
			new UseModel{Name="出栏",Value=5},
			new UseModel{Name="淘汰",Value=6},
			new UseModel{Name="补栏",Value=7},
			new UseModel{Name="调并",Value=8},
			new UseModel{Name="健康检测",Value=9}
		};

		public void InitData()
		{
			var regionIndex = Region.HasValue ? Region.Value : 0; if (regionIndex < 0) regionIndex = 0;
			var areaName = AreaArray[regionIndex];
			var dto = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeCageDtoProce(areaName);

			GeLongGuanLi = dto.GeLongGuanLi;
			JianKangJianCha = dto.JiangKangJianCha;
			ChaDan = dto.ChaDan;
			ZhaoDan = dto.ZhaoDan;
			ChaChu = dto.ChaChu;
			ChuLan = dto.ChuLan;
			TaoTai = dto.TaoTai;
			TiaoBing = dto.TiaoBing;
			BuLan = dto.BuLan;
			KongZhigeLong = dto.KongZhigeLong;
			TempErr=dto.TempErr;
		}

		private static int PageSize { get; set; } = 50;
		public PigeonPageViewModel()
		{
			HasDan = 0;
			HasRuGe = 0;
			Region = 0;
			MaxPageCount = 10;
			PageIndex = 1;
			InitData();
			QueryCage();


		}




		[RelayCommand]
		public void QueryCage()
		{
			
			var regionIndex = Region.HasValue ? Region.Value : 0; if (regionIndex < 0) regionIndex = 0;
			var hasegg = HasDan.HasValue ? HasDan.Value : 0; if (hasegg < 0) hasegg = 0;
			var haschild = HasRuGe.HasValue ? HasRuGe.Value : 0; if (haschild < 0) haschild = 0;
			var haswendu=WenDu.HasValue ? WenDu.Value : 0; if (haswendu < 0) haswendu = 0;
			var condition = new PigeonCondition
			{
				Region = AreaArray[regionIndex],
				CageNumber = CageNumber,
				CageStatus = CageStatus,
				HasEgg = hasegg,
				HasRuGe = haschild,
				TempStatus=haswendu

			};

			var res = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeonCageQueryList(condition, PageIndex, PageSize);
			MaxPageCount = (res.total + PageSize - 1) / PageSize;
			if (PigeonCages.Count > 0) PigeonCages.Clear();
			res.lst.ForEach(x =>
			{
				x.background = "#0000";
				if (!string.IsNullOrWhiteSpace(x.Temperature))
				{
					var arr=x.Temperature.Replace("[","").Replace("]","").Replace("'","").Replace("\"","").Split(new string[] { ",","，"}, StringSplitOptions.RemoveEmptyEntries).Select(x=>decimal.Parse(x));
					if(arr.Any(m=>m>AppRuntime.MaxTemperature||m<AppRuntime.MinTemperature)) x.IsAbnormal = true;
					if (x.IsAbnormal)
					{
						x.background = "red";
					}
				}
				PigeonCages.Add(x);
			});
			InitData();
		}


		[RelayCommand]

		public void OutportCage()
		{
			var regionIndex = Region.HasValue ? Region.Value : 0; if (regionIndex < 0) regionIndex = 0;
			var hasegg = HasDan.HasValue ? HasDan.Value : 0; if (hasegg < 0) hasegg = 0;
			var haschild = HasRuGe.HasValue ? HasRuGe.Value : 0; if (haschild < 0) haschild = 0;
			var haswendu = WenDu.HasValue ? WenDu.Value : 0; if (haswendu < 0) haswendu = 0;
			var condition = new PigeonCondition
			{
				Region = AreaArray[regionIndex],
				CageNumber = CageNumber,
				CageStatus = CageStatus,
				HasEgg = hasegg,
				HasRuGe = haschild,
				TempStatus = haswendu

			};
			var res = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeonCageQueriyAll(condition);
			var newres = new List<PigeonCageExcel>();
			res.ForEach(x =>
			{
				var tt = new PigeonCageExcel
				{
					Temperature = x.Temperature,
					Id= x.Id,
					Arrange=x.Arrange,
					Building = x.Building,
					DailyGrams = x.DailyGrams,
					EggCount = x.EggCount,
					EggDate= x.EggDate,
					EggDay= x.EggDay,
					Group=x.Group,
					IsFertilization=x.IsFertilization,
					PigeonCount= x.PigeonCount,
					Number= x.Number,
					RuGeCount= x.RuGeCount,
					RuGeDay= x.RuGeDay,
					ChildDate = x.ChildDate,
					PigeonDate= x.PigeonDate,

				};
				newres.Add(tt);
			});
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.Filter = "*.xlsx|*.*";
			if(saveFileDialog.ShowDialog()==DialogResult.OK){
				var path=saveFileDialog.FileName;
				if (!path.EndsWith(".xlsx"))
				{
					path += ".xlsx";
				}
				MiniExcel.SaveAs(path, newres);
			}
			

		}

		[RelayCommand]
		public async Task ImportCage()
		{

			var fileDialog=new OpenFileDialog();
			fileDialog.Filter = "*.xlsx|*.*";
			if (fileDialog.ShowDialog() == DialogResult.OK)
			{
				try
				{
					var path = fileDialog.FileName;
					var datas = MiniExcel.Query<PigeonCageExcel>(path);
					ImportCageData2DB(datas);
				}
				catch(Exception ex)
				{
					Growl.ErrorGlobal(ex.Message);
				}
			

			}
		}



		public void ImportCageData2DB(IEnumerable<PigeonCageExcel> lst)
		{
			if (lst == null || lst.Count() <= 0) return;
			var cages = new List<PigeonCageQuery>();
			lst.ForEach(x =>
			{
				var tt = new PigeonCageQuery
				{
					Temperature = x.Temperature,
					Id = x.Id,
					Arrange = x.Arrange,
					Building = x.Building,
					DailyGrams = x.DailyGrams,
					EggCount = x.EggCount,
					EggDate = x.EggDate,
					EggDay = x.EggDay,
					Group = x.Group,
					IsFertilization = x.IsFertilization,
					PigeonCount = x.PigeonCount,
					Number = x.Number,
					RuGeCount = x.RuGeCount,
					RuGeDay = x.RuGeDay,
					ChildDate = x.ChildDate,
					PigeonDate = x.PigeonDate,


				};
				cages.Add(tt);

			});
			var res= AppRuntime.GetService().GetService<PigeonCageService>().ImpoertPigeonCageData(cages);
			if (res.IsError)
			{
				Growl.ErrorGlobal(res.msg);
			}
		}


		public void ExportErrorCage()
		{
			var res = AppRuntime.GetService().GetService<AgvCarService>().GetTodayAgvErrorData();
			var first = res.First.Select(x => new AgvErrorFeedData
			{
				CarNumber = x.CarNumber,
				CreateTime = x.CreateTime,
				BarCode = x.BarCode,
				FeedNumber = x.FeedNumber,
				FeedTotal = x.FeedTotal,
				ServoUseStatus = x.ServoUseStatus,
				CageNumber = $"{x.BarCode.Substring(0,1)}-{x.BarCode.Substring(1,2)}-{x.BarCode.Substring(3,3)}-{x.BarCode.Substring(6,2)}"
			}).ToList();
			var second = res.Second.Select(x => new AgvErrorFeedData
			{
				CarNumber = x.CarNumber,
				CreateTime = x.CreateTime,
				BarCode = x.BarCode,
				FeedNumber = x.FeedNumber,
				FeedTotal = x.FeedTotal,
				ServoUseStatus = x.ServoUseStatus,
				CageNumber = $"{x.BarCode.Substring(0, 1)}-{x.BarCode.Substring(1, 2)}-{x.BarCode.Substring(3, 3)}-{x.BarCode.Substring(6, 2)}"
			}).ToList();
			var third = res.Third.Select(x => new AgvErrorFeedData
			{
				CarNumber = x.CarNumber,
				CreateTime = x.CreateTime,
				BarCode = x.BarCode,
				FeedNumber = x.FeedNumber,
				FeedTotal = x.FeedTotal,
				ServoUseStatus = x.ServoUseStatus,
				CageNumber = $"{x.BarCode.Substring(0, 1)}-{x.BarCode.Substring(1, 2)}-{x.BarCode.Substring(3, 3)}-{x.BarCode.Substring(6, 2)}"
			}).ToList();
			var sheets = new Dictionary<string, object>
			{
				["第一次喂料"]=first,
				["第二次喂料"]=second,
				["第三次喂料"]=third,

			};
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.Filter = "*.xlsx|*.*";
			if (saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				var path = saveFileDialog.FileName;
				if (!path.EndsWith(".xlsx"))
				{
					path += ".xlsx";
				}
				MiniExcel.SaveAs(path, sheets);
			}
		}






	}

	public class AreaModel
	{
		public string Name { get; set; }
		public string Value { get; set; }
	}
	public class PigeonCageExcel
	{
		[ExcelColumnName("二维码")]
		public string Id { get; set; }
		/// <summary>
		/// 栋
		/// </summary>
		[ExcelColumnName("栋")]
		public string Building { get; set; }
		/// <summary>
		/// 列
		/// </summary>
		[ExcelColumnName("列")]
		public string Arrange { get; set; }
		/// <summary>
		/// 组
		/// </summary>
		[ExcelColumnName("组")]
		public string Group { get; set; }
		/// <summary>
		/// 号
		/// </summary>
		[ExcelColumnName("号")]
		public string Number { get; set; }

		[ExcelColumnName("鸽笼编号")]
		public string CageNumber => $"{Building}-{Arrange}-{Group}-{Number}";

		[ExcelColumnName("种鸽数")]
		public int? PigeonCount { get; set; }

		[ExcelColumnName("种鸽入笼时间")]
		public DateTime? PigeonDate { get; set; }

		[ExcelColumnName("乳鸽数")]
		public int? RuGeCount { get; set; }

		[ExcelColumnName("乳鸽出生日期")]
		public DateTime? ChildDate { get; set; }

		[ExcelColumnName("乳鸽天数")]
		public int? RuGeDay { get; set; }

		[ExcelColumnName("鸽蛋数量")]
		public int? EggCount { get; set; }
		[ExcelColumnName("鸽蛋日期")]
		public DateTime? EggDate { get; set; }
		[ExcelColumnName("鸽蛋天数")]
		public int? EggDay { get; set; }

		[ExcelColumnName("是否受精")]
		public bool? IsFertilization { get; set; }

		[ExcelColumnName("喂料量")]
		public decimal? DailyGrams { get; set; }

		[ExcelColumnName("温度")]
		public string? Temperature { get; set; }
		
	}

	public class AgvErrorFeedData
	{

		/// <summary>
		/// 当前二维码
		/// </summary>
		[ExcelColumnName("二维码")]
		public string? BarCode { get; set; }
		[ExcelColumnName("鸽笼编号")]
		public string? CageNumber { get; set; }
		[ExcelColumnName("喂料量")]
		public string? FeedTotal { get; set; }

		/// <summary>
		/// 第几次喂料
		/// </summary>
		[ExcelColumnName("第几次喂料")]
		public int FeedNumber { get; set; }
		[ExcelColumnName("小车编号")]
		public string? CarNumber { get; set; }


		/// <summary>
		/// 伺服启用状态
		/// </summary>
		[ExcelColumnName("伺服状态")]
		public int ServoUseStatus { get; set; }

		/// <summary>
		/// 创建时间
		/// </summary>
		[ExcelColumnName("创建时间")]
		public string? CreateTime { get; set; }


		
	}
}
